package systemConfigController

import (
	"arabApi/app/api/controllers"
	"arabApi/app/api/controllers/CFun"
	"arabApi/app/api/requests"
	"arabApi/app/api/requests/CRequest"
	"arabApi/app/api/requests/systemConfigRequest"
	"arabApi/app/api/services/CService"
	"arabApi/app/api/services/systemConfigService"
	"arabApi/pkg/helpers"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/spf13/cast"
)

type SystemConfig struct {
	controllers.BaseAPIController
}

func (sc SystemConfig) List(c *gin.Context) {

	systemReq := systemConfigRequest.SystemConfigRequest{}
	if err := c.ShouldBindQuery(&systemReq); err != nil {
		CFun.Ajax_return_fail(c, CFun.WithMsg("解析异常"))
		return
	}

	data := gin.H{}
	data["list"], data["count"] = systemConfigService.List(systemReq)

	CFun.Ajax_return_success(c, CFun.WithData(data))
}

func (sc SystemConfig) SystemMsg(c *gin.Context) {
	request := CRequest.Oid{}

	// 解析 JSON 请求
	if err := c.ShouldBindQuery(&request); err != nil {
		CFun.Ajax_return_fail(c, CFun.WithMsg(err.Error()))
		return
	}

	if ok := requests.Validate(c, &request, CRequest.CheckID); !ok {
		return
	}

	system := systemConfigService.GetMsgById(cast.ToInt64(request.Id))
	CFun.Ajax_return_success(c, CFun.WithData(system))
}

func (sc SystemConfig) Add(c *gin.Context) {

	systemReq := systemConfigRequest.SysAdd{}
	if err := c.ShouldBindBodyWith(&systemReq, binding.JSON); err != nil {
		CFun.Ajax_return_fail(c, CFun.WithMsg("解析异常"+err.Error()))
		return
	}

	var id uint64

	if systemReq.Id > 0 {
		if err := systemConfigService.Update(systemReq); err != nil {
			CFun.Ajax_return_fail(c, CFun.WithMsg("添加错误"))
			return
		} else {
			CFun.Ajax_return_success(c)
		}
	} else {
		if id = systemConfigService.Add(systemReq); id == 0 {
			CFun.Ajax_return_fail(c, CFun.WithMsg("添加错误"))
			return
		} else {
			data := gin.H{}
			data["Id"] = id

			CFun.Ajax_return_success(c, CFun.WithData(data))
		}
	}

}

func (sc SystemConfig) Update(c *gin.Context) {

	systemReq := systemConfigRequest.SysAdd{}
	if err := c.ShouldBindBodyWith(&systemReq, binding.JSON); err != nil {
		CFun.Ajax_return_fail(c, CFun.WithMsg("解析异常"+err.Error()))
		return
	}

	if err := systemConfigService.Update(systemReq); err != nil {
		CFun.Ajax_return_fail(c, CFun.WithMsg("添加错误"))
		return
	} else {
		CFun.Ajax_return_success(c)
	}
}

func (sc SystemConfig) Del(c *gin.Context) {

	request := CRequest.Oid{}

	// 解析 JSON 请求
	if err := c.ShouldBindQuery(&request); err != nil {
		CFun.Ajax_return_fail(c, CFun.WithMsg(err.Error()))
		return
	}

	if ok := requests.Validate(c, &request, CRequest.CheckID); !ok {
		return
	}

	if err := systemConfigService.Del(cast.ToInt64(request.Id)); err != nil {
		CFun.Ajax_return_fail(c, CFun.WithMsg("删除失败"+err.Error()))
	}
	CFun.Ajax_return_success(c)
}

func (sc SystemConfig) State(c *gin.Context) {

	state := CService.State_kai_guan

	stateArr := helpers.S_map_to_array(state)

	CFun.Ajax_return_success(c, CFun.WithData(stateArr))
}
